package postgres

import (
	"context"
	"fmt"
	"go.uber.org/zap"
	"gorm.io/gorm"
	logger "ota/collector/logger"
	"ota/config"
	"ota/errors"
	"ota/model"
	"ota/model/entity"
	"ota/utils"
)

var UpgradeStrategy = &upgradeStrategy{&execTx{}}

type upgradeStrategy struct {
	IExecTx
}

func init() {
	Register(UpgradeStrategy)
}

func (a *upgradeStrategy) Init() {
	if config.Conf.AutoMigrate {
		p := &entity.UpgradeStrategy{}
		if dbOta.Migrator().HasTable(p) {
			logger.Debug("table already exist: ", zap.String("table", p.TableName()))
			return
		}
		if err := dbOta.AutoMigrate(p); err != nil {
			logger.Error("filed to create table please check config or manually create", zap.String("table", p.TableName()), zap.String("err", err.Error()))
		} else {
			logger.Info("create table successfully", zap.String("table", p.TableName()))
		}
	}
}

// Create
func (a *upgradeStrategy) Create(ctx context.Context, m *entity.UpgradeStrategy) (int64, error) {
	err := GetDB(ctx).Create(m).Error
	return m.Id, err
}

// Find detail
func (a *upgradeStrategy) Find(ctx context.Context, in *model.UpgradeStrategyInfoRequest) (*entity.UpgradeStrategy, error) {
	e := &entity.UpgradeStrategy{}

	q := GetDB(ctx).Model(&entity.UpgradeStrategy{})

	if in.Id == 0 {
		return e, errors.New("condition illegal")
	}
	err := q.First(&e, in.Id).Error
	return e, err
}

// Update
func (a *upgradeStrategy) Update(ctx context.Context, id int64, dict map[string]interface{}) error {
	return GetDB(ctx).Model(&entity.UpgradeStrategy{}).Where("id = ?", id).Updates(dict).Error
}

// Delete
func (a *upgradeStrategy) Delete(ctx context.Context, id int64) error {
	return GetDB(ctx).Delete(&entity.UpgradeStrategy{}, id).Error
}

// List query list
func (a *upgradeStrategy) List(ctx context.Context, in *model.UpgradeStrategyListRequest, opts ...model.QueryOptions) (int, []*entity.UpgradeStrategy, error) {

	var (
		opt              = model.GetQueryOption(opts...)
		q                = GetDB(ctx).Model(&entity.UpgradeStrategy{})
		err              error
		total            int64
		upgradeStrategys []*entity.UpgradeStrategy
	)

	if in.Id != nil {

		q = q.Where("id = ?", in.Id)

	}

	if in.FirmwareId != nil {

		q = q.Where("? = ANY(firmware_ids)", *in.FirmwareId)

	}

	if in.FirmwareIds != nil {

		q = q.Where("firmware_ids && ARRAY[?]::bigint[]", in.FirmwareIds)

	}

	if in.Name != nil {

		q = q.Where("name like ?", utils.SqlLike(in.Name))

	}

	if in.UpgradeType != nil {

		q = q.Where("upgrade_type = ?", in.UpgradeType)

	}

	if in.Order != nil {

		q = q.Where("order = ?", in.Order)

	}

	if in.FailureNotifyMethod != nil {

		q = q.Where("failure_notify_method = ?", in.FailureNotifyMethod)

	}

	if in.RetryCount != nil {

		q = q.Where("retry_count = ?", in.RetryCount)

	}

	if in.CreatedAt != nil {

		q = q.Where("created_at = ?", in.CreatedAt)

	}

	if in.UpdatedAt != nil {

		q = q.Where("updated_at = ?", in.UpdatedAt)

	}
	if len(opt.SelectFields) > 0 {
		q = q.Select(opt.SelectFields)
	}

	if len(opt.OrderFields) > 0 {
		q = q.Order(fmt.Sprintf("%v", model.ParseOrder(opt.OrderFields)))
	}

	b := !opt.OnlyCount && !opt.OnlyList
	if opt.OnlyCount || b {
		if err = q.Count(&total).Error; err != nil {
			return 0, nil, err
		}
	}

	if opt.OnlyList || b {
		if err = q.Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&upgradeStrategys).Error; err != nil {
			return 0, nil, err
		}
	}

	return int(total), upgradeStrategys, nil
}

// ExecTransaction execute database transaction
func (a *upgradeStrategy) ExecTransaction(ctx context.Context, callback func(ctx context.Context) error) error {
	return GetDB(ctx).Transaction(func(tx *gorm.DB) error {
		ctx = context.WithValue(ctx, ContextTxKey, tx)
		return callback(ctx)
	})
}
